package com.System.servlet;

import com.System.pojo.User;
import com.System.service.UserImpl.UserService;
import com.System.untils.SaltMD5Util;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private com.System.service.User service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String checkCode=request.getParameter("checkCode");
        HttpSession session = request.getSession();
        String target =(String) session.getAttribute("checkCode");
        if(!checkCode.equals(target)){
            request.setAttribute("register_msg","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }

        User user=new User();
        user.setUserName(username);
        user.setPassWord(password);
        User result = service.selectTarget(user);

        if(result==null){
            service.registerUser(new User(username, SaltMD5Util.generateSaltPassword(password)));
            request.setAttribute("register_msg","注册成功,请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            request.setAttribute("register_msg","用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}